package com.rd.teacher.jichao.day13;

import java.util.ArrayList;
import java.util.List;

public class TestVolatile {

    public static void main(String[] args) {
        // 虽然创建了相同的MyList对象
        // 但是线程1对其添加元素  线程2不可见 不能判断出长度后退出
        MyList myList = new MyList();
        Thread1 t1 = new Thread1(myList);
        t1.start();

        Thread2 t2 = new Thread2(myList);
        t2.start();
    }
}

class MyList {
//    private volatile List<String> list = new ArrayList<>();
    private List<String> list = new ArrayList<>();

    // 线程1使用  写操作
    public void add(String str) {
        list.add(str);
    }

    // 线程2使用  读操作
    public int size() {
        return list.size();
    }
}

class Thread1 extends Thread {

    MyList list;

    public Thread1(MyList list) {
        super();
        this.list = list;
    }

    @Override
    public void run() {
        // 添加元素
        try {
            for (int i = 0; i < 10; i++) {
                list.add(i + "");
                System.out.println(getName() + "添加了元素" + i);
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }
}

class Thread2 extends Thread {

    MyList list;

    public Thread2(MyList list) {
        super();
        this.list = list;
    }

    @Override
    public void run() {
        // 轮询元素个数
        while (true) {
//            System.out.println(getName() + "轮询list的长度为：" + list.size());
            if (list.size() == 5) {
                System.out.println("此线程可以退出");
                throw new RuntimeException();
            }
        }
    }
}